#include "ctool.h"
#include "tool.h"
ctool::ctool(QObject *parent):QObject(parent){}

QByteArrayList ctool::processingCommunicationInformationCenter(QByteArray communicationInformationList)
{
     QByteArrayList balResult;
    QByteArrayList clientToServiceCoomunicationByteArrayList
        =byteArrayTolist(communicationInformationList,this->dedicatedDelimiter);
    for(size_t i=0;i<clientToServiceCoomunicationByteArrayList.size();i++){
        balResult.append(processingCommunicationInformation(clientToServiceCoomunicationByteArrayList[i]));
    }
    return balResult;

}




QByteArray ctool::processingCommunicationInformation(QByteArray communicationInformation)
{
    QByteArray byteArraycCopy=communicationInformation;
    QJsonDocument jsonDoc=QJsonDocument::fromJson(byteArraycCopy);
    if(jsonDoc.isObject()){
        QJsonObject jsonOBJ=jsonDoc.object();
        QStringList jsonKEYS=jsonOBJ.keys();
        if(!jsonKEYS.contains("action"))
            return "";//无action 信息错误
        switch (identifierOfProcessedInformation[jsonOBJ["action"].toString()]) {
        case 0:{//Login 登录
            // qDebug()<<"1;";
            QString acc= jsonOBJ["acc"].toString();
            QString psw=jsonOBJ["psw"].toString();
            QString newPsw= Tool::getStaticTool()->getDatabaseTool()->findPSWforACC(acc);
            QJsonObject jsonObjToSend;
            jsonObjToSend.insert("action","LoginBack");
            if(newPsw==psw&&newPsw!=""){
                jsonObjToSend.insert("code","1");
                QMap<QString,QString> map= Tool::getStaticTool()->getDatabaseTool()->getUserDetailInformation(acc);
                if(map.size()){
                    for(auto it =map.begin();it!=map.end();it++){
                        jsonObjToSend.insert(it.key(),it.value());
                    }
                }
            }else{
                jsonObjToSend.insert("code","0");
            }
            QJsonDocument jsonDoc(jsonObjToSend);
            QByteArray byteArrayToSend=jsonDoc.toJson();
            return byteArrayToSend;
            // qDebug()<<byteArrayToSend;
            // clientSocket->write(byteArrayToSend+dedicatedDelimiter);
            break;
        }


        default:{
            break;

        }

        }
    }
    return "";
}

QByteArrayList ctool::byteArrayTolist(QByteArray byteArray, QByteArray dedicateDelimter)
{
    long long from=0;
    int size=dedicateDelimter.size();
    QByteArrayList targetByteArrayList;
    while(from<byteArray.size()-1){
        long long endOfSegmentedCharacter=byteArray.indexOf(dedicateDelimter,from);
        QByteArray partByteArray=byteArray.mid(from,endOfSegmentedCharacter);
        targetByteArrayList.append(partByteArray);
        from=endOfSegmentedCharacter+size;
    }
    return targetByteArrayList;
}

